package com.wh.wisdomsite.xbox.server.controller.wo;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.wo.attendDetail.AttendDetailIn;
import com.wh.wisdomsite.xbox.pojo.wo.attendDetail.AttendDetailOut;
import com.wh.wisdomsite.xbox.pojo.wo.attendDetail.PersonCountArray;
import com.wh.wisdomsite.xbox.pr.entity.Project;
import com.wh.wisdomsite.xbox.pr.service.IProjectService;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.utils.Const;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.server.connToserver_HttpClientClose;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 考勤详情列表controller
 * @author 刘旭
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.server.controller.wo
 * @date 2018年09月25日 8:53
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Controller
@RequestMapping(value = "/attendDetail")
public class AttendDetailController {
    private static final Log logger = LogFactory.getLog(AttendDetailController.class);

    @Autowired
    private IProjectService iProjectService;

    /**
     * 跳转到考勤详细信息列表
     * @param request
     * @param attendDetailIn
     * @return
     */
    @RequiresPermissions("rules:wo_attendDetail_page")
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index(HttpServletRequest request, AttendDetailIn attendDetailIn) {
        request.setAttribute("attendDetail",attendDetailIn);
        return "wo/attendDetail/attendDetailList";
    }

    /**
     * 获取考勤详细信息列表
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:wo_attendDetail_find")
    @RequestMapping(value = "/attendDetailList.do")
    public void attendDetailList(HttpServletResponse response, AttendDetailIn in) {
        logger.info("加载考勤详细信息列表-->>开始");
        try {
            //身份证号
            String idCardIn = in.getIdCard();
            String projectIdIn = in.getProjectId();
            Page<Project> page = new Page<Project>();
            page.setCurrent(1);
            page.setSize(Integer.MAX_VALUE);
            //设置获取项目条件
            EntityWrapper<Project> ewProject = new EntityWrapper<Project>();
            ewProject.setEntity(new Project());
            //若不是超级管理员则根据用户权限添加查询条件
            if (!UserUtils.isSysAdmin()) {
                ewProject = UserUtils.setEntityWrapper(ewProject, "c1", "o1", "p");
            }
            ewProject.groupBy("p.prId");
            //获取项目集合
            Page<Map<String, Object>> projectPage = iProjectService.getMapsPage(page, ewProject);
            JSONArray array = new JSONArray();
            //将项目id和项目名称存入projectMap
            Map<String,String> projectMap = new HashMap<String,String>();
            if (projectPage.getRecords().size() > 0) {
                for (Map<String, Object> project : projectPage.getRecords()) {
                    String projectId = (String) project.get("prId");
                    String projectName = (String) project.get("prName");
                    projectMap.put(projectId,projectName);
                }
            }
            if (StringUtils.isNotEmpty(idCardIn) && StringUtils.isNotEmpty(projectIdIn)) {
                //设置接口查询条件
                Map<String, String> map = new HashMap<String, String>();
                map.put("idCard", idCardIn);
                map.put("projectId", projectIdIn);
                map.put("startTime", in.getStartTime());
                map.put("endTime", in.getEndTime());
                //通过接口获取数据
                String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_ATTENDMANAGERDETAILURL, map);
                if(result.contains("projectId")){
                    result = result.replaceAll("Work","work").replaceAll("Group","group").replaceAll("null","\"\"");
                }
                //对象中存在集合的需要通过map注明集合的类型，否则会报错
                Map classMap = new HashMap();
                classMap.put("persons", PersonCountArray.class);
                classMap.put("punchTimes", String.class);
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                AttendDetailOut attendDetailList = (AttendDetailOut)net.sf.json.JSONObject.toBean(jsonObject, AttendDetailOut.class,classMap);
                //人员考勤信息
                List<PersonCountArray> personCountArray = attendDetailList.getPersonCount().getPersons();
                for(PersonCountArray personCount : personCountArray){
                    String attendTime = personCount.getAttendDate();
                    List<String> timeList = personCount.getPunchTimes();
                    //把出勤时间合并在一起
                    String time1 = "";
                    if(StringUtils.isNotEmpty(attendTime)){
                        for(String time : timeList){
                            String timeStr = time.replace(attendTime+" ","");
                            StringBuilder  sb = new StringBuilder (timeStr);
                            sb.insert(8,"-");
                            time1 = time1 + sb.toString() + ",";
                        }
                    }
                    String timeResult = "";
                    if(time1.length() > 0){
                        timeResult = time1.substring(0,time1.length()-1);
                    }
                    JSONObject jsonObj = new JSONObject(personCount);
                    String projectId = personCount.getPerson().getProjectId();
                    String projectName = projectMap.get(projectId);
                    jsonObj.put("projectName",projectName);
                    jsonObj.put("timeResult",timeResult);
                    array.put(jsonObj);
                }
            }
            ResManager.getJsonOut(response).print(array);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取考勤详细信息列表-->Exception " + e.getMessage());
        }
    }

}
